import { inject, onUnmounted, ref } from 'vue'
import { isFunction } from 'lodash-es'
import AMapLoader from '@amap/amap-jsapi-loader'

export function useMapInit(mapId) {
  const AMap: any = ref(null)
  const mapInstance: any = ref(null)
  const mouseTool: any = ref(null)
  const satellite: any = ref(null)

  function initMap(cb) {
    window._AMapSecurityConfig = {
      securityJsCode: '5b7145f7d9ed035be937fa85984d96f6',
    }

    AMapLoader.load({
      key: '31677c7de087cd59d18ae0ad305b182e',
      version: '2.0',
      plugins: [
        'AMap.ToolBar',
        'AMap.Scale',
        'AMap.MouseTool',
        'AMap.MoveAnimation',
        'AMap.DistrictSearch',
        'AMap.TileLayer',
        'AMap.Geolocation',
        'AMap.Marker',
      ],
    })
      .then((am) => {
        AMap.value = am

        mapInstance.value = new AMap.value.Map(mapId, {
        })

        satellite.value = new AMap.value.TileLayer.Satellite({
          zIndex: 1,
        })

        mouseTool.value = new AMap.value.MouseTool(mapInstance.value)

        isFunction(cb) ? cb() : ''
      })
      .catch((e) => {
        console.log('initMap-Error:', e)
      })
  }

  onUnmounted(() => {
    mapInstance.value?.destroy()
  })

  return { initMap, mapInstance, AMap, mouseTool, satellite }
}
